package com.ekuaitu.kuaitustaff.activity;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ekuaitu.kuaitustaff.R;
import com.ekuaitu.kuaitustaff.adapter.CarPopStateAdapter;
import com.ekuaitu.kuaitustaff.api.ApiService;
import com.ekuaitu.kuaitustaff.api.ApiStore;
import com.ekuaitu.kuaitustaff.api.UrlConstant;
import com.ekuaitu.kuaitustaff.application.MyApplication;
import com.ekuaitu.kuaitustaff.base.BaseActivity;
import com.ekuaitu.kuaitustaff.bean.FindRecentReportBean;
import com.ekuaitu.kuaitustaff.bean.ResultBean;
import com.ekuaitu.kuaitustaff.bean.StaffOrderBean;
import com.ekuaitu.kuaitustaff.bean.UploadImageBaidu;
import com.ekuaitu.kuaitustaff.utils.AntiShake;
import com.ekuaitu.kuaitustaff.utils.AppManager;
import com.ekuaitu.kuaitustaff.utils.Constants;
import com.ekuaitu.kuaitustaff.utils.ImageLoader;
import com.ekuaitu.kuaitustaff.utils.IntentKey;
import com.ekuaitu.kuaitustaff.utils.IntentUtil;
import com.ekuaitu.kuaitustaff.utils.Logger;
import com.ekuaitu.kuaitustaff.utils.SDCardUtils;
import com.ekuaitu.kuaitustaff.utils.SPKey;
import com.ekuaitu.kuaitustaff.utils.SPUtils;
import com.ekuaitu.kuaitustaff.utils.ToastUtils;
import com.ekuaitu.kuaitustaff.utils.UploadPicUtil;
import com.ekuaitu.kuaitustaff.utils.ble.BleConstants;
import com.ekuaitu.kuaitustaff.utils.ble.BluetoothHelper;
import com.ekuaitu.kuaitustaff.widget.WheelView;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.ekuaitu.kuaitustaff.utils.ble.BluetoothHelper.REQUEST_OPEN_BLE_ONCE;

public class CarCheckStateActivity extends BaseActivity {

    @BindView(R.id.edt_beizhu)
    EditText edt_beizhu;
    @BindView(R.id.tv_sure)
    TextView tv_sure;
    @BindView(R.id.tv_ble_opendoor)
    TextView tv_ble_opendoor;
    @BindView(R.id.tv_state)
    TextView tv_state;
    @BindView(R.id.rl_select)
    RelativeLayout rl_select;

    @BindView(R.id.iv_leftfront)
    ImageView iv_leftfront;
    @BindView(R.id.iv_rightback)
    ImageView iv_rightback;
    @BindView(R.id.iv_front)
    ImageView iv_front;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.linear_takephoto)
    LinearLayout linear_takephoto;
    @BindView(R.id.tv_car_break)
    TextView tvCarBreak;


    private TextView pop_tv_cancel;
    private TextView pop_tv_finish;
    private WheelView pop_wheelview;
    private PopupWindow selectPopWindow;
    private View popwindow_select;
    private Context mContext = this;
    private CarPopStateAdapter stateAdapter;
    private List<String> list = new ArrayList<String>();
    private String orderId, carId, shortName, licenseTag;
    private int selectType;
    private View layout_view;
    private int submitType;
    private File compressFile;
    private String[] picKeyArray = new String[]{"", "", "", ""};
    private boolean flag, flag1, flag2, flag3, flag4;
    private Uri imageUri;
    private StaffOrderBean.AttachmentBean.ActionBean actionBean;

    private Intent intent;
    private File outputImage;
    private BleConstants.OperateType operateType;

    private String key;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case 1:
                    showLoadingDialog();
                    break;
                case 2:
                    dismissLoadingDialog();
                    //成功压缩
                    Logger.d("checkCar", "压缩成功" + compressFile.getName());
                    //上传图片
                    uploadImage(compressFile);

                    if (submitType == 0) {
                        ImageLoader.getInstance().displayImage(mContext, compressFile, iv_leftfront);
                        flag1 = true;
                    } else if (submitType == 1) {
                        ImageLoader.getInstance().displayImage(mContext, compressFile, iv_rightback);
                        flag2 = true;
                    } else if (submitType == 2) {
                        ImageLoader.getInstance().displayImage(mContext, compressFile, iv_front);
                        flag3 = true;
                    } else {
                        ImageLoader.getInstance().displayImage(mContext, compressFile, iv_back);
                        flag4 = true;
                    }
                    if (flag1 && flag2 && flag3 && flag4) {
                        flag = true;
                        checkSelectType();
                    }

                    break;
                case 3:
                    //压缩失败
                    dismissLoadingDialog();
                    Logger.d("checkCar", "压缩失败" + compressFile.getName());
                    break;
                case 4: //上传成功
                    Logger.d("checkCar", "上传成功" + compressFile.getName());
                    SPUtils.getInstance(mContext).putStringValue(SPKey.CHECK_CAR_PIC_NAME, SPUtils.getInstance(mContext).getStringValue(SPKey.CHECK_CAR_PIC_NAME) + "," + compressFile.getName());
                    Logger.d("checkCar", "上传成功总共" + SPUtils.getInstance(mContext).getStringValue(SPKey.CHECK_CAR_PIC_NAME));
                    break;
                case 5://上传失败
                    Logger.d("checkCar", "上传失败" + compressFile.getName());
                    break;
                case 6:
                    Logger.d("checkCar", "上传取消" + compressFile.getName());
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private File fileDir;
    public boolean carBreak = false;

    @Override
    protected int getLayoutId() {
        layout_view = View.inflate(mContext, R.layout.activity_car_checkstate, null);
        return R.layout.activity_car_checkstate;
    }

    @Override
    protected void initView() {
        //初始化
        SPUtils.getInstance(mContext).removeValue(SPKey.CHECK_CAR_PIC_NAME);
        fileDir = new File(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "checkcar");
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        File[] files = fileDir.listFiles();
        if (files != null) {
            Arrays.sort(files);
            for (int i = 0; i < files.length; i++) {
                if (files[i].getName().endsWith("jpg")) {
                    files[i].delete();
                }
            }
        }
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        initPopWindowView();
        orderId = getIntent().getStringExtra(IntentKey.INTENT_ORDER_ID);
        carId = getIntent().getStringExtra(IntentKey.INTENT_CAR_ID);
        shortName = getIntent().getStringExtra(IntentKey.INTENT_TASKTYPE);
        licenseTag = getIntent().getStringExtra(IntentKey.INTENT_LICENSETAG);

        rl_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击输入备注 再点击选择类型 会覆盖
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                }
                selectPopWindow.showAtLocation(layout_view, Gravity.BOTTOM, 0, 0);
                backgroundAlpha(0.7f);

            }
        });
        edt_beizhu.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                checkSelectType();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        tv_sure.setClickable(false);//初始化
        tv_sure.setBackgroundResource(R.drawable.btn_gray_bg);
        if ("19".equals(shortName)) {//洗车工单
            rl_select.setClickable(false);
            tv_state.setText(list.get(list.size() - 1));
            selectType = 3;
            linear_takephoto.setVisibility(View.VISIBLE);
            edt_beizhu.setVisibility(View.GONE);
            tvCarBreak.setVisibility(View.GONE);
        } else if ("25".equals(shortName) || "26".equals(shortName) || "27".equals(shortName)) {//维修工单
            rl_select.setClickable(false);
            tv_state.setText(list.get(list.size() - 2));
            rl_select.setVisibility(View.GONE);
            selectType = 2;
            linear_takephoto.setVisibility(View.VISIBLE);
            edt_beizhu.setVisibility(View.VISIBLE);
            tvCarBreak.setVisibility(View.GONE);
        } else {
            rl_select.setClickable(true);
            linear_takephoto.setVisibility(View.GONE);
            edt_beizhu.setVisibility(View.VISIBLE);
            tvCarBreak.setVisibility(View.GONE);
        }
    }


    @OnClick({R.id.tv_car_break, R.id.title_back, R.id.tv_sure, R.id.tv_ble_opendoor, R.id.iv_leftfront, R.id.iv_rightback, R.id.iv_front, R.id.iv_back})
    public void onClick(View view) {
        if (AntiShake.check(view.getId())) return; //判断是否多次点击
        switch (view.getId()) {
            case R.id.title_back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.iv_leftfront:
                submitType = 0;
                checkperssionAndCamera();
                break;
            case R.id.iv_rightback:
                submitType = 1;
                checkperssionAndCamera();
                break;
            case R.id.iv_front:
                submitType = 2;
                checkperssionAndCamera();
                break;
            case R.id.iv_back:
                submitType = 3;
                checkperssionAndCamera();
                break;
            case R.id.tv_ble_opendoor:
                //蓝牙开车门
                operateType = BleConstants.OperateType.OPEN_DOOR_POWER;
                if (BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
                    showLoadingDialog();
                    //蓝牙开，未连接
                    if (BluetoothHelper.getInstance().isBluetoothOpened() && !BluetoothHelper.getInstance().isConnect()) {
                        controlCar("open", "开门检查", "开门检查");
                        BluetoothHelper.getInstance().searchDevice(true, "扫描连接", 1, bothSearchResponse);
                    }
                    //蓝牙开，已连接
                    else if (BluetoothHelper.getInstance().isBluetoothOpened() && BluetoothHelper.getInstance().isConnect()) {
                        BluetoothHelper.getInstance().operateCar(true, "开门供电", operateType, onOperateCarListener);
                    }
                    //蓝牙未开
                    else if (!BluetoothHelper.getInstance().isBluetoothOpened()) {
                        BluetoothHelper.getInstance().openBluetooth(CarCheckStateActivity.this, REQUEST_OPEN_BLE_ONCE);
                    }

                } else {
                    controlCar("open", "开门检查", "开门检查");
                    BluetoothHelper.getInstance().getBleInfo(carId, orderId, licenseTag, mContext, null);
                }
                break;
            case R.id.tv_sure:
                if ((selectType == 2 || selectType == 3)) {
                    if ("19".equals(shortName) || "25".equals(shortName) || "26".equals(shortName) || "27".equals(shortName)) {
                        //洗车工单和维修工单没有车损
                        checkCanStaffOrder();
                    } else {
                        findRecentReport();
                    }
                } else {
                    checkCanStaffOrder();
                }
                break;
            case R.id.tv_car_break:
                CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.setCookie(UrlConstant.Request.CAR_BREAK, "orderId=" + orderId);
                cookieManager.setCookie(UrlConstant.Request.CAR_BREAK, "phoneNum=" + SPUtils.getInstance(mContext).getStringValue(SPKey.USER_PHONE_NUM) + "");
                cookieManager.setCookie(UrlConstant.Request.CAR_BREAK, "carId=" + carId);
                cookieManager.setCookie(UrlConstant.Request.CAR_BREAK, "license=" + licenseTag);
                IntentUtil.toWebViewActivity(mContext, UrlConstant.Request.CAR_BREAK);
                break;
        }
    }

    private void findRecentReport() {
        showLoadingDialog();
        JSONObject bodyJson = new JSONObject();
        try {
            bodyJson = new JSONObject(new Gson().toJson(((MyApplication) getApplication()).getRequestFieldMap()));
            bodyJson.put("staffOrderId", orderId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).findRecentReport(body).enqueue(new Callback<FindRecentReportBean>() {
            @Override
            public void onResponse(Call<FindRecentReportBean> call, Response<FindRecentReportBean> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getResult().getCode() == 200) {
                    edt_beizhu.setText(response.body().getResult().getAttachment().getRemark());
                    checkCanStaffOrder();
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, "请上报车辆损伤相关信息", ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<FindRecentReportBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void submitCarBreakSuccess(ResultBean resultBean) {
        carBreak = true;
        checkSelectType();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    // 初始化popwindow
    private void initPopWindowView() {
        list.add("车况无问题");
        list.add("车况有问题但可运营");
        list.add("车况有问题且不可运营");
        popwindow_select = View.inflate(this, R.layout.pop_select, null);
        pop_tv_cancel = (TextView) popwindow_select.findViewById(R.id.pop_tv_cancel);
        pop_tv_finish = (TextView) popwindow_select.findViewById(R.id.pop_tv_finish);
        pop_wheelview = (WheelView) popwindow_select.findViewById(R.id.wheel1);

        stateAdapter = new CarPopStateAdapter(mContext, list, "openCheck");
        pop_wheelview.setAdapter(stateAdapter);

        selectPopWindow = new PopupWindow(popwindow_select,
                RadioGroup.LayoutParams.FILL_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT, true);
        selectPopWindow.setAnimationStyle(R.style.popwindow_in_out);
        selectPopWindow.setBackgroundDrawable(getResources().getDrawable(
                R.color.colorPrimary));// 设置弹出窗口的背景
        // 点击空白处时，隐藏掉pop窗口
        selectPopWindow.setFocusable(true);
        selectPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                backgroundAlpha(1f);

            }
        });
        pop_tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectPopWindow.dismiss();
            }
        });
        pop_tv_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectPopWindow.dismiss();
                tv_state.setText(list.get(pop_wheelview.getSelectedItemPosition()));
                selectType = pop_wheelview.getSelectedItemPosition() + 1;
                checkSelectType();
            }
        });
    }

    private void checkSelectType() {
        if (selectType == 2) {
            linear_takephoto.setVisibility(View.VISIBLE);
            if ("25".equals(shortName) || "26".equals(shortName) || "27".equals(shortName)) {//维修工单没有车损入口，selectType == 2，隐藏
                tvCarBreak.setVisibility(View.GONE);
                edt_beizhu.setVisibility(View.VISIBLE);
                if (flag && !TextUtils.isEmpty(edt_beizhu.getText().toString())) {//维修工单有备注
                    tv_sure.setClickable(true);
                    tv_sure.setBackgroundResource(R.drawable.btn_bg);
                } else {
                    tv_sure.setClickable(false);
                    tv_sure.setBackgroundResource(R.drawable.btn_gray_bg);
                }
            } else {
                tvCarBreak.setVisibility(View.VISIBLE);
                edt_beizhu.setVisibility(View.GONE);
                if (flag) {
                    tv_sure.setClickable(true);
                    tv_sure.setBackgroundResource(R.drawable.btn_bg);
                } else {
                    tv_sure.setClickable(false);
                    tv_sure.setBackgroundResource(R.drawable.btn_gray_bg);
                }
            }

        } else if (selectType == 3) {
            linear_takephoto.setVisibility(View.VISIBLE);
            edt_beizhu.setVisibility(View.GONE);
            if ("19".equals(shortName)) {//洗车工单没有车损入口，selectType ==3 ,不可选择
                if (flag) {
                    tv_sure.setClickable(true);
                    tv_sure.setBackgroundResource(R.drawable.btn_bg);
                } else {
                    tv_sure.setClickable(false);
                    tv_sure.setBackgroundResource(R.drawable.btn_gray_bg);
                }
            } else {
                tvCarBreak.setVisibility(View.VISIBLE);
                if (flag) {
                    tv_sure.setClickable(true);
                    tv_sure.setBackgroundResource(R.drawable.btn_bg);
                } else {
                    tv_sure.setClickable(false);
                    tv_sure.setBackgroundResource(R.drawable.btn_gray_bg);
                }
            }
        } else if (selectType == 1) {//选择第一个时候，无拍照，车辆无问题，无车损，备注不用校验
            linear_takephoto.setVisibility(View.GONE);
            tvCarBreak.setVisibility(View.GONE);
            edt_beizhu.setVisibility(View.VISIBLE);
            tv_sure.setClickable(true);
            tv_sure.setBackgroundResource(R.drawable.btn_bg);
        }
    }

    private void checkCanStaffOrder() {
        showLoadingDialog();
        if ((selectType == 3 || selectType == 2)) {
            List<String> success = new ArrayList<>();
            if (SPUtils.getInstance(mContext).getStringValue(SPKey.CHECK_CAR_PIC_NAME) != null) {
                success = Arrays.asList(SPUtils.getInstance(mContext).getStringValue(SPKey.CHECK_CAR_PIC_NAME).split(","));
            }
            File[] files = fileDir.listFiles();
            List<File> unUpdatePics = new ArrayList<>();
            if (files != null) {
                Arrays.sort(files);
                for (int i = 0; i < files.length; i++) {
                    if (files[i].getName().endsWith("jpg") && !success.contains(files[i].getName())) {
                        unUpdatePics.add(files[i]);
                    }
                }
            }
            if (unUpdatePics.size() != 0) {
                Observable
                        .fromIterable(unUpdatePics)
                        .flatMap(new Function<File, ObservableSource<UploadImageBaidu>>() {
                            @Override
                            public ObservableSource<UploadImageBaidu> apply(File file) throws Exception {
                                return Observable.create(new ObservableOnSubscribe<UploadImageBaidu>() {
                                    @Override
                                    public void subscribe(ObservableEmitter<UploadImageBaidu> emitter) throws Exception {
                                        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).uploadImageBaidu(((MyApplication) getApplication()).getRequestFieldMap(), "stsToken", "upload").enqueue(new Callback<UploadImageBaidu>() {
                                            @Override
                                            public void onResponse(Call<UploadImageBaidu> call, Response<UploadImageBaidu> response) {
                                                Logger.d("checkCar", "预备上传" + response.body().getAttachment().getBucketName());
                                                response.body().setFile(file);
                                                emitter.onNext(response.body());
                                                emitter.onComplete();
                                            }

                                            @Override
                                            public void onFailure(Call<UploadImageBaidu> call, Throwable t) {
                                                emitter.onComplete();
                                            }
                                        });
                                    }
                                });
                            }
                        })
                        .flatMap(new Function<UploadImageBaidu, ObservableSource<File>>() {
                            @Override
                            public ObservableSource<File> apply(UploadImageBaidu uploadImageBaidu) throws Exception {

                                return Observable.create(new ObservableOnSubscribe<File>() {
                                    @Override
                                    public void subscribe(ObservableEmitter<File> emitter) throws Exception {
                                        Logger.d("checkCar", "上传 开始" + uploadImageBaidu.getFile() + "   " + uploadImageBaidu.getAttachment().getBucketName());
                                        key = getFileNameNoExOrder(uploadImageBaidu.getFile());
                                        UploadPicUtil.getInstance().uploadPicToBos(
                                                uploadImageBaidu.getFile(),
                                                uploadImageBaidu.getAttachment().getAk(),
                                                uploadImageBaidu.getAttachment().getSk(),
                                                uploadImageBaidu.getAttachment().getBucketName(),
                                                uploadImageBaidu.getAttachment().getStsToken(),
                                                uploadImageBaidu.getAttachment().getBucketName(),
                                                key,
                                                new UploadPicUtil.OnFinishListener() {
                                                    @Override
                                                    public void onSuccess() {
                                                        SPUtils.getInstance(mContext).putStringValue(SPKey.CHECK_CAR_PIC_NAME, SPUtils.getInstance(mContext).getStringValue(SPKey.CHECK_CAR_PIC_NAME) + "," + uploadImageBaidu.getFile().getName());
                                                        emitter.onNext(uploadImageBaidu.getFile());
                                                        emitter.onComplete();
                                                        Logger.d("checkCar", "上传成功" + uploadImageBaidu.getFile().getName());
                                                    }

                                                    @Override
                                                    public void onFailure(String failReason) {
                                                        emitter.onComplete();
                                                        Logger.d("checkCar", "上传失败" + uploadImageBaidu.getFile().getName());
                                                    }
                                                });
                                    }
                                });
                            }
                        }).subscribe(new Observer<File>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(File file) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        stafforder();
                    }
                });
            } else {
                stafforder();
            }

        } else {
            stafforder();
        }
    }

    //提交
    private void stafforder() {
        showLoadingDialog();
        HashMap<String, String> eventMap = new HashMap<>();
        eventMap.put("action", "开门检查提交接口");
        eventMap.put("comment", "开门检查提交接口");
        eventMap.put("car", licenseTag);
        new ApiStore().getApiService(UrlConstant.Request.BASE_URL_NEW, "v/stafforder/new/checkCarB4DealOrder", eventMap, new ApiStore.ParseCallBack() {
            @Override
            public void onSaveFailure(String error) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, error, ToastUtils.LENGTH_SHORT).show();
            }

            @Override
            public void onSaveSuccess(ApiService apiService) {
                apiService.stafforder(((MyApplication) getApplication()).getRequestFieldMap(), orderId, carId, selectType + "", edt_beizhu.getText().toString(), picKeyArray[0], picKeyArray[1], picKeyArray[2], picKeyArray[3])
                        .enqueue(new Callback<StaffOrderBean>() {
                            @Override
                            public void onResponse(Call<StaffOrderBean> call, Response<StaffOrderBean> response) {
                                if (response.isSuccessful() && response.body() != null) {
                                    dismissLoadingDialog();
                                    if (response.body().getErrCode() == 0) {
                                        try {
                                            //清除照片
                                            SPUtils.getInstance(mContext).removeValue(SPKey.CHECK_CAR_PIC_NAME);
                                            File[] files = fileDir.listFiles();
                                            if (files != null) {
                                                Arrays.sort(files);
                                                for (int i = 0; i < files.length; i++) {
                                                    if (files[i].getName().endsWith("jpg")) {
                                                        files[i].delete();
                                                    }
                                                }
                                            }
                                            ToastUtils.makeText(mContext, response.body().getMessage(), 0, ToastUtils.LENGTH_LONG).show();
                                            //有问题且不可运营 没有actionBean值
                                            if (selectType != 3) {
                                                actionBean = response.body().getAttachment().getAction();
                                            }

                                            intent = new Intent();
                                            intent.putExtra("actionBean", actionBean);
                                            setResult(Constants.REQUEST_CAR_STATE, intent);
                                            AppManager.getAppManager().finishActivity();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    } else if (response.body().getErrCode() == 11) {
                                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                                        intent = new Intent(mContext, LoginNewActivity.class);
                                        startActivity(intent);
                                        AppManager.getAppManager().finishAllActivity();
                                    } else {
                                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                                    }
                                } else {
                                    dismissLoadingDialog();
                                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onFailure(Call<StaffOrderBean> call, Throwable t) {
                                dismissLoadingDialog();
                                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                                Log.i("neterror", "开门检查提交" + t.toString());
                            }
                        });
            }
        });
    }


    public void checkperssionAndCamera() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionLists = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.CAMERA);
            }
            if (!permissionLists.isEmpty()) {//有拒绝的权限
                ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), Constants.PERMISSION_REQUEST_CAMERA);
            } else {
                takePhoto();
            }
        } else {
            takePhoto();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    }

    private void takePhoto() {
        // 创建File对象，用于存储拍照后的图片
        outputImage = new File(getExternalCacheDir(), "output_image.jpg");
        Logger.i("checkCar", getExternalCacheDir() + "");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT < 24) {
            imageUri = Uri.fromFile(outputImage);
        } else {
            imageUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", outputImage);
        }
        // 启动相机程序
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, submitType);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("imageUrl", MyApplication.imageUrl);
        outState.putString("orderId", orderId);
        outState.putString("carId", carId);
        outState.putString("shortName", shortName);
        outState.putString("licenseTag", licenseTag);
        outState.putStringArray("picKeyArray", picKeyArray);
        outState.putBoolean("flag", flag);
        outState.putBoolean("flag1", flag1);
        outState.putBoolean("flag2", flag2);
        outState.putBoolean("flag3", flag3);
        outState.putBoolean("flag4", flag4);
        outState.putInt("submitType", submitType);
        outState.putBoolean("carBreak", carBreak);

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        outputImage = new File(getExternalCacheDir(), "output_image.jpg");
        MyApplication.imageUrl = savedInstanceState.getString("imageUrl");
        orderId = savedInstanceState.getString("orderId");
        carId = savedInstanceState.getString("carId");
        shortName = savedInstanceState.getString("shortName");
        licenseTag = savedInstanceState.getString("licenseTag");
        picKeyArray = savedInstanceState.getStringArray("picKeyArray");
        flag = savedInstanceState.getBoolean("flag");
        flag1 = savedInstanceState.getBoolean("flag1");
        flag2 = savedInstanceState.getBoolean("flag2");
        flag3 = savedInstanceState.getBoolean("flag3");
        flag4 = savedInstanceState.getBoolean("flag4");
        submitType = savedInstanceState.getInt("submitType");
        carBreak = savedInstanceState.getBoolean("carBreak");
        if (!TextUtils.isEmpty(picKeyArray[0])) {
            ImageLoader.getInstance().displayImage(getApplicationContext(),
                    MyApplication.imageUrl + picKeyArray[0], iv_leftfront);
        }
        if (!TextUtils.isEmpty(picKeyArray[1])) {
            ImageLoader.getInstance().displayImage(getApplicationContext(),
                    MyApplication.imageUrl + picKeyArray[1], iv_rightback);
        }
        if (!TextUtils.isEmpty(picKeyArray[2])) {
            ImageLoader.getInstance().displayImage(getApplicationContext(),
                    MyApplication.imageUrl + picKeyArray[2], iv_front);
        }
        if (!TextUtils.isEmpty(picKeyArray[3])) {
            ImageLoader.getInstance().displayImage(getApplicationContext(),
                    MyApplication.imageUrl + picKeyArray[3], iv_back);
        }
        checkSelectType();
        //fix null point bug
        edt_beizhu = findViewById(R.id.edt_beizhu);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK && requestCode == REQUEST_OPEN_BLE_ONCE) {
            dismissLoadingDialog();
        } else if (resultCode == RESULT_OK && requestCode == REQUEST_OPEN_BLE_ONCE) {
            showLoadingDialog();
            BluetoothHelper.getInstance().searchDevice(true, "扫描连接", 1, bothSearchResponse);
        } else if (resultCode == RESULT_OK && requestCode == submitType) {
            try {
                Luban.with(mContext)
                        .load(outputImage)  //传入要压缩的图片
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                Message message = new Message();
                                message.arg1 = 1;
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onSuccess(File file) {
                                Message message = new Message();
                                message.arg1 = 2;
                                Logger.i("checkCar-rename1", file.getAbsolutePath());
                                File[] files = fileDir.listFiles();
                                if (files != null) {
                                    Arrays.sort(files);
                                    for (int i = 0; i < files.length; i++) {
                                        if (files[i].getName().endsWith("jpg") && files[i].getName().startsWith(submitType + "-" + orderId + "-")) {
                                            files[i].delete();//有了就删除，只保留submitType对应的一张
                                        }
                                    }
                                }
                                compressFile = new File(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "checkcar" + File.separator + submitType + "-" + orderId + "-" + SDCardUtils.createReturnCarFileName(MyApplication.getInstance().getUserId()) + ".jpg");
                                file.renameTo(compressFile);
                                picKeyArray[submitType] = getFileNameNoExOrder(compressFile);
                                Logger.i("checkCar-rename2", compressFile.getAbsolutePath());
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onError(Throwable e) {
                                Message message = new Message();
                                message.arg1 = 3;
                                handler.sendMessage(message);
                            }
                        }).launch();    //启动压缩
            } catch (Exception e) {
                Message message = new Message();
                message.arg1 = 3;
                handler.sendMessage(message);
                e.printStackTrace();
            }
        }
    }


    /*
     * Java文件操作 获取不带扩展名的文件名
     */
    public String getFileNameNoExOrder(File nameFile) {
        String filename = nameFile.getName();
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                int index = filename.lastIndexOf("-");
                return filename.substring(index + 1, dot);
            }
        }
        return filename;
    }

    private void uploadImage(final File picFile) {
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).uploadImageBaidu(((MyApplication) getApplication()).getRequestFieldMap(), "stsToken", "upload").enqueue(new Callback<UploadImageBaidu>() {
            @Override
            public void onResponse(Call<UploadImageBaidu> call, Response<UploadImageBaidu> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getErrCode() == 0) {
                        key = getFileNameNoExOrder(picFile);
                        UploadPicUtil.getInstance().uploadPicToBos(picFile, response.body().getAttachment().getAk(),
                                response.body().getAttachment().getSk(), response.body().getAttachment().getBucketName(),
                                response.body().getAttachment().getStsToken(),
                                response.body().getAttachment().getBucketName(),
                                key, new UploadPicUtil.OnFinishListener() {
                                    @Override
                                    public void onSuccess() {
                                        Message message = new Message();
                                        message.arg1 = 4;
                                        Bundle b = new Bundle();
                                        message.setData(b);
                                        handler.sendMessage(message);
                                    }

                                    @Override
                                    public void onFailure(String failReason) {
                                        Message message = new Message();
                                        message.arg1 = 5;
                                        Bundle b = new Bundle();
                                        b.putString("failReason", failReason);
                                        message.setData(b);
                                        handler.sendMessage(message);
                                    }
                                });

                    } else {
                        Message message = new Message();
                        message.arg1 = 5;
                        handler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.arg1 = 5;
                    handler.sendMessage(message);
                }
            }

            @Override
            public void onFailure(Call<UploadImageBaidu> call, Throwable t) {
                Message message = new Message();
                message.arg1 = 5;
                handler.sendMessage(message);
            }
        });
    }

    BluetoothHelper.BothSearchResponse bothSearchResponse = new BluetoothHelper.BothSearchResponse() {
        @Override
        public void onSearchSuccess(String mac, String bleName) {
            BluetoothHelper.getInstance().connectDevice(connectResponse, 1);
        }

        @Override
        public void onSearchTimeout() {
            dismissLoadingDialog();
            Logger.i("bleinfo", "扫描超时,开门检查");
            ApiStore.bleRecord("2", orderId, carId, "connect");
        }

        @Override
        public void onSearchTimeoutEveryTime() {

        }
    };

    /**
     * 蓝牙连接的结果
     */
    BluetoothHelper.BothConnectResponse connectResponse = new BluetoothHelper.BothConnectResponse() {
        @Override
        public void onConnectSuccess() {
            dismissLoadingDialog();
            Logger.i("bleinfo", "连接上了,开门检查");
            ApiStore.bleRecord("1", orderId, carId, "connect");

        }

        @Override
        public void onConnectFailed(String error) {
            dismissLoadingDialog();
            ApiStore.bleRecord("2", orderId, carId, "connect");

        }

        @Override
        public void onConnectTimeoutEveryTime() {

        }
    };
    BluetoothHelper.OnOperateCarListener onOperateCarListener = new BluetoothHelper.OnOperateCarListener() {
        @Override
        public void onOperateSuccess(int[] status) {
            dismissLoadingDialog();
            if (operateType == BleConstants.OperateType.OPEN_DOOR_POWER) {
                ToastUtils.makeText(mContext, "开门成功", ToastUtils.LENGTH_SHORT).show();
            } else {
                ToastUtils.makeText(mContext, "操作成功", ToastUtils.LENGTH_SHORT).show();
            }
            ApiStore.bleRecord("1", orderId, carId, "open");
        }

        @Override
        public void onOperateFailure(String error) {
            dismissLoadingDialog();
            ApiStore.bleRecord("2", orderId, carId, "open");
            controlCar("open", "开门检查", "开门检查");
        }
    };

    // 锁车 开车的请求接口
    private void controlCar(final String command, String action, String comment) {
        showLoadingDialog();
        HashMap<String, String> eventMap = new HashMap<>();
        eventMap.put("action", action);
        eventMap.put("comment", comment);
        eventMap.put("car", licenseTag);
        eventMap.put("order", orderId);
        eventMap.put("command", command);

        new ApiStore().getApiService(UrlConstant.Request.BASE_URL_NEW, "v/car/control", eventMap, new ApiStore.ParseCallBack() {

            @Override
            public void onSaveFailure(String error) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, error, ToastUtils.LENGTH_SHORT).show();
            }

            @Override
            public void onSaveSuccess(ApiService apiService) {
                apiService.controlCar(MyApplication.getInstance().getRequestFieldMap(), orderId, carId, command, "1")
                        .enqueue(new Callback<ResultBean>() {
                            @Override
                            public void onResponse(Call<ResultBean> call, final Response<ResultBean> response) {
                                try {
                                    if (response.isSuccessful() && response.body() != null) {
                                        dismissLoadingDialog();
                                        if (response.body().getErrCode() == 0) {
                                            ToastUtils.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                                        } else if (response.body().getErrCode() == 11) {
                                            intent = new Intent(mContext, LoginNewActivity.class);
                                            startActivity(intent);
                                            AppManager.getAppManager().finishAllActivity();
                                        } else {
                                            dismissLoadingDialog();
                                            ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();

                                        }
                                    } else {
                                        dismissLoadingDialog();
                                        ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }


                            @Override
                            public void onFailure(Call<ResultBean> call, Throwable t) {
                                dismissLoadingDialog();
                                ToastUtils.makeText(mContext, getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                                Log.i("Throwable", t.toString());
                            }
                        });
            }
        });
    }
}
